﻿﻿<template>

  <div ref="readerContainer" class="content" :style="{ backgroundColor: backgroundColor, color: textColor, fontFamily: fontFamily, fontSize: fontSize + 'px' }">

    <van-nav-bar

        :title="pname"

        left-arrow

        @click-left="onBack"

        fixed

    >

      <template #right>

        <van-icon name="ellipsis" size="24" @click="toggleMenu" />

      </template>

    </van-nav-bar>

    <!-- 章节标题 -->

    <h1>{{ a.title }}</h1>

    <!-- 广告banner -->

    <h5 style="background-color: #f0f0f0; padding: 10px; margin-top: 20px;">购买汪汪VIP享受纯净阅读体验！</h5>

    <div id="aliyun-ad" class="aliyun-ad-container">

      <div v-if="bannerList.length > 0" class="ad-container">

        <a :href="getCurrentAd() && getCurrentAd().url" target="_blank" class="ad-link">

          {{ getCurrentAd() && getCurrentAd().name }} - ￥{{ getCurrentAd() && getCurrentAd().price }}

        </a>

      </div>

      <div v-else class="ad-placeholder">

        <p>广告加载中...充值SVIP即可屏蔽）</p>

      </div>

    </div>

    <!-- 显示电子书内容 -->

    <div v-html="a.content"></div>



    <!-- 新增的未购买章节提示弹出层 -->

    <van-popup v-model="isPurchasePopupVisible" position="center" :style="{ width: '80%' }" :close-on-click-overlay="false">

      <div style="padding: 20px;">

        <p>该章节为VIP章节，购买后才可阅读哦~</p>

        <p>当前用户剩余金币: {{ user.userglod1 }} 金币</p>

        <p>注: 一章节10金币</p>

        <div style="text-align: center;">

          <van-button type="default" @click="closePurchasePopup1">取消</van-button>

          <van-button type="primary" @click="purchaseChapter">购买</van-button>

        </div>

      </div>

    </van-popup>



    <!-- 使用 Vant2 的 Popup 弹出层 -->

    <van-popup v-model="isMenuVisible" position="bottom" :style="{ height: '30%' }">

      <ul>

        <li><a href="#" @click.prevent="setBackgroundColor('white')">白</a></li>

        <li><a href="#" @click.prevent="setBackgroundColor('yellow')">黄</a></li>

        <li><a href="#" @click.prevent="setBackgroundColor('black')">黑</a></li>

        <li><a href="#" @click.prevent="setFontFamily('Arial')">Arial</a></li>

        <li><a href="#" @click.prevent="setFontFamily('Times New Roman')">Times New Roman</a></li>

        <li><a href="#" @click.prevent="setFontFamily('Courier New')">Courier New</a></li>

        <li><a href="#" @click.prevent="setFontSize(14)">小</a></li>

        <li><a href="#" @click.prevent="setFontSize(16)">中</a></li>

        <li><a href="#" @click.prevent="setFontSize(18)">大</a></li>

      </ul>

    </van-popup>



    <!-- 上一章按钮 -->

    <button @click="prevChapter" :disabled="chapterId <= 1">上一章</button>



    <!-- 下一章按钮 -->

    <button @click="nextChapter">下一章</button>



    <h4>广告Banner火爆招商中，请关注！</h4>

  </div>

</template>







<script>

export default {

  data() {

    return {

      a: {
        content: '', // 电子书内容
        title: '',    // 电子书标题
      },
      vip: 0, // 章节是否为VIP章节
      pname: '',     // 电子书名称
      chapterId: 0, // 初始章节ID
      isMenuVisible: false, // 菜单是否可见
      backgroundColor: 'white', // 默认背景颜色为白色
      textColor: 'black', // 默认文字颜色为黑色
      fontFamily: 'Arial', // 默认字体
      fontSize: 16, // 默认字体大小
      pid: 0, // 书籍ID
      bannerList: [], // 广告列表
      currentAdIndex: 0, // 当前显示广告的索引
      purchase: false, // 是否购买
      isLoadingNextChapter: false, // 是否正在加载下一章
      user: {}, // 用户信息
      id: 0 ,// 用户ID
      isPurchasePopupVisible: false, // 新增状态变量，控制未购买章节提示弹出层的显示
    };
  },
  methods: {
    /**
     * 关闭未购买章节提示弹出层
     */
    closePurchasePopup() {
      this.isPurchasePopupVisible = false;
    },
    closePurchasePopup1() {
      this.onBack()
      this.isPurchasePopupVisible = false;
    },
    /**
     * 显示未购买章节提示弹出层
     */
    showPurchasePopup() {
      this.isPurchasePopupVisible = true;
    },
    onBack() {
      this.$router.go(-1); // 返回上一页
    },

    findOneUser(id){
      this.axios.get(`http://localhost:9999/api-user/user/findOneUser?id=`+id).then(res => {
        this.user = res.data;
        console.log('this.user:', this.user);
      })
    },

    /**
     * 购买章节
     */
    purchaseChapter() {
      this.axios.post(`http://localhost:9999/api-user/user/purchase?id=${this.id}&userglod1=10`).then(res => {
        if (res.data.code === 1) {
          this.axios.post(`http://localhost:9999/api-user/user/addPurchase?id=${this.id}&chapterId=${this.chapterId}&amount=10&pid=${this.pid}&pname=${this.pname}&title=${this.a.title}`).then(res => {
            if (res.data.code === 1) {
              this.$toast('购买成功');
              this.closePurchasePopup();
              this.fetchChapter(); // 重新加载章节内容
            } else {
              this.$toast('购买失败，请稍后再试~');
            }
          });
        } else {
          this.$toast('购买失败，请稍后再试~');
        }
      });
    },

    /**

     * 请求指定章节的内容

     * @returns {Promise} 返回一个 Promise 对象

     */

    fetchChapter() {
      return this.axios.get(`http://localhost:9999/api-novel/books/list1?pid=${this.pid}&chapterId=${this.chapterId}`).then(res => {
        console.log('res:', res); // 打印完整响应对象
        console.log('res.data:', res.data); // 打印响应数据
        // 确保 res.data 是一个数组，并且每个元素都是对象
        if (Array.isArray(res.data) && res.data.length > 0) {
          const firstItem = res.data[0];
          this.vip = res.data[0].vip; // 章节是否为VIP章节
          console.log('this.vip:', this.vip);
          if (this.vip === 2) {
            this.axios.get(`http://localhost:9999/api-user/user/findPurchase?uid=${this.id}&pid=${this.pid}&chapterId=${this.chapterId}`).then(res => {
              if (res.data.code === 1) {
                this.purchase = true;
              } else {
                this.showPurchasePopup(); // 显示未购买章节提示弹出层
              }
            });
          } else if (this.vip === 1) {
            this.$toast('该章节为免费章节，请慢慢阅读哦~');
          } else {
            this.$toast('您已购买此章节，请慢慢阅读哦~');
          }

          // 章节内容和标题
          if (typeof firstItem.content === 'string' && typeof firstItem.title === 'string') {
            this.a = firstItem;
          } else {
            console.warn('Unexpected response structure or content type');
          }
        } else {
          console.warn('Unexpected response data format');
        }
        console.log(this.a); // 打印当前章节内容
      })
          .catch(error => {
            console.error('请求失败:', error);
          });
    },



    /**
     * 切换到上一章
     */
    prevChapter() {
      if (this.chapterId > 1) {
        this.chapterId--;
        this.fetchChapter().then(() => {
          this.scrollToTop();
        });
      }
    },
    /**
     * 切换到下一章，并滚动到顶部
     */
    nextChapter() {
      if (!this.isLoadingNextChapter) {
        this.isLoadingNextChapter = true;
        this.chapterId ++;
        this.fetchChapter().then(() => {
          this.scrollToTop();
          this.isLoadingNextChapter = false;
        });
        this.axios.post("http://localhost:9999/api-task/dailyTasks/updateChapterNumber?userId="+this.id).then(res=>{
          console.log("章节数+1")
        })
      }

    },



    /**

     * 滚动到页面顶部

     */

    scrollToTop() {

      this.$refs.readerContainer.scrollTop = 0;

    },



    /**

     * 切换菜单的显示状态

     */

    toggleMenu() {

      this.isMenuVisible = !this.isMenuVisible;

      console.log('Toggle menu to', this.isMenuVisible);

    },

    // toggleMenu(event) {

    //   const rect = this.$refs.readerContainer.getBoundingClientRect();

    //   const centerX = rect.left + rect.width / 2;

    //   const centerY = rect.top + rect.height / 2;

    //
    //   console.log('Click coordinates:', event.clientX, event.clientY);
    //   console.log('Center coordinates:', centerX, centerY);
    //
    //   if (
    //       event.clientX >= centerX - 50 &&
    //       event.clientX <= centerX + 50 &&
    //       event.clientY >= centerY - 50 &&
    //       event.clientY <= centerY + 50
    //   ) {
    //     this.isMenuVisible = !this.isMenuVisible;
    //     console.log('Toggle menu to', this.isMenuVisible);
    //   }
    // },

    /**

     * 设置背景颜色并相应调整文字颜色

     */

    setBackgroundColor(color) {

      this.backgroundColor = color;

      if (color === 'black') {

        this.textColor = 'white';

      } else {

        this.textColor = 'black';

      }

      this.isMenuVisible = false; // 关闭菜单

    },



    /**

     * 设置字体

     */

    setFontFamily(font) {

      this.fontFamily = font;

      this.isMenuVisible = false; // 关闭菜单

    },



    /**

     * 设置字体大小

     */

    setFontSize(size) {

      this.fontSize = size;

      this.isMenuVisible = false; // 关闭菜单

    },



    // 请求广告数据

    banner() {

      this.axios.post('http://localhost:9999/api-tagclass-service/banner/list')

          .then(res => {

            this.bannerList = res.data;

            this.startAdRotation(); // 获取广告数据后启动广告轮播

          })

          .catch(error => {

            console.error('请求失败:', error);

          });

    },



    // 启动广告轮播

    startAdRotation() {

      if (this.bannerList.length > 0) {

        setInterval(() => {

          // 随机选择一条广告

          this.currentAdIndex = Math.floor(Math.random() * this.bannerList.length);

        }, 5000); // 每5秒切换一次广告

      }

    },



    // 获取当前广告数据

    getCurrentAd() {

      if (this.bannerList.length === 0) {

        return null;

      }

      return this.bannerList[this.currentAdIndex];

    },

  },

  created() {
    let pid = this.$route.query.pid;
    let cId = this.$route.query.id;
    this.chapterId = cId;
    console.log('Fetching chapter ID:', this.chapterId); // 打印当前章节ID
    this.pid = pid;
    try {
      this.id=JSON.parse(localStorage.getItem("user")).id;
      this.fetchChapter(); // 初始化时加载第一章
      this.findOneUser(this.id)
    }catch (error) {
      this.$router.go(-1);
      this.$toast("请先登录");
    }
    // 定义一个映射对象，用于存储 pid 和书名的对应关系
    const bookMapping = {
      1: '雪中悍刀行',
      2: '遮天',
      3: '完美世界',
      4: '圣墟',
      5: '剑来',
      6: '神印王座II皓月当空',
      7: '阿司匹林',
      8: '都市狂飙',
      9: '东风第一枝',
      10: '庆余年',
      11: '大魏皇叔',
      12: '侯爷的掌心娇是朵黑心莲'
    };
    console.log('PID:', this.pid); // 打印 PID
    this.pname = bookMapping[this.pid];
    // 应用到 Vue 组件中
    console.log('Book Name:', this.pname);
    this.banner();



  },

  // mounted() {

  //   // 监听滚动事件，当滚动到底部时，自动加载下一章

  //   this.$refs.readerContainer.addEventListener('scroll', () => {

  //     const scrollTop = this.$refs.readerContainer.scrollTop;

  //     const scrollHeight = this.$refs.readerContainer.scrollHeight;

  //     const clientHeight = this.$refs.readerContainer.clientHeight;

  //

  //     if (scrollTop + clientHeight >= scrollHeight) {

  //       this.nextChapter();

  //     }

  //   });

  // }

};

</script>



<style scoped>

.content {

  white-space: pre-wrap;

  word-wrap: break-word;

  padding: 20px;

  box-sizing: border-box;

  height: 100vh;

  overflow-y: auto;

  position: relative; /* 使子元素绝对定位相对于此元素 */

}

.aliyun-ad-container {

  text-align: center;

  margin: 20px 0;

}



.ad-container {

  display: inline-block;

}



.ad-link {

  text-decoration: none;

  color: #0073e6;

  font-size: 16px;

  font-weight: bold;

  padding: 10px;

}



.ad-link:hover {

  text-decoration: underline;

  color: #005bb5;

}



.ad-placeholder {

  font-size: 14px;

  color: #aaa;

}

button {

  margin-top: 10px;

  padding: 10px 20px;

  font-size: 16px;

  cursor: pointer;

}



button:disabled {

  opacity: 0.5;

  cursor: not-allowed;

}



/* 添加章节标题样式 */

h1 {

  text-align: center;

  margin-bottom: 20px;

}



/* 菜单样式 */

.menu {

  display: none;

  position: absolute;

  top: 50%;

  left: 50%;

  transform: translate(-50%, -50%);

  background-color: white;

  border: 1px solid #ccc;

  padding: 10px;

  z-index: 1000;

  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

}



.menu.show {

  display: block;

}



.menu ul {

  list-style-type: none;

  padding: 0;

}



.menu li {

  margin: 5px 0;

}



.menu a {

  text-decoration: none;

  color: black;

  cursor: pointer;

}



.menu a:hover {

  text-decoration: underline;

}

.van-popup {

  padding: 10px;

}



.van-popup ul {

  list-style-type: none;

  padding: 0;

}



.van-popup li {

  margin: 5px 0;

}



.van-popup a {

  text-decoration: none;

  color: black;

  cursor: pointer;

}



.van-popup a:hover {

  text-decoration: underline;

}

</style>
